package com.applancer.notification;

import java.io.IOException;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;

public class RegisterInBackground {

	/**
	 * Registers the application with GCM servers asynchronously.
	 * <p>
	 * Stores the registration ID and app versionCode in the application's
	 * shared preferences.
	 */

	public RegisterInBackground() {

		register a = new register();
		a.execute();

	}

	class register extends AsyncTask<Void, String, String> {

		ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(GcmData.act,
					"Doing stuff. Please wait...", null);
		}

		@Override
		protected String doInBackground(Void... params) {
			String msg = "";
			try {
				if (GcmData.gcm == null) {
					GcmData.gcm = GoogleCloudMessaging.getInstance(GcmData.act);
				}
				GcmData.regid = GcmData.gcm.register(GcmData.SENDER_ID);
				msg = "Device registered, registration ID=" + GcmData.regid;

				// You should send the registration ID to your server over HTTP,
				// so it can use GCM/HTTP or CCS to send messages to your app.
				// The request to your server should be authenticated if your
				// app
				// is using accounts.
				sendRegistrationIdToBackend();

				// For this demo: we don't need to send it because the device
				// will send upstream messages to a server that echo back the
				// message using the 'from' address in the message.

				// Persist the regID - no need to register again.
				storeRegistrationId(GcmData.act, GcmData.regid);
			} catch (IOException ex) {
				msg = "Error :" + ex.getMessage();
				// If there is an error, don't just keep trying to register.
				// Require the user to click a button again, or perform
				// exponential back-off.
			}
			return msg;
		}

		@Override
		protected void onPostExecute(String msg) {
			dialog.dismiss();
			MethodNeedToBeOverridedAfterAsyncTaskComplete();
			Log.i(GcmData.TAG, GcmData.regid + "");
		}

	}

	protected void MethodNeedToBeOverridedAfterAsyncTaskComplete() {
	};

	private void sendRegistrationIdToBackend() {
		// Your implementation here.
	}

	private void storeRegistrationId(Context context, String regId) {
		final SharedPreferences prefs = GcmData.getGCMPreferences(context);
		int appVersion = GcmData.getAppVersion(context);
		Log.i(GcmData.TAG, "Saving regId on app version " + appVersion);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(GcmData.PROPERTY_REG_ID, regId);
		editor.putInt(GcmData.PROPERTY_APP_VERSION, appVersion);
		editor.commit();
	}

}
